﻿// -----------------------------------------------------------------------
// <copyright file="SessionHandler.cs" company="SoftServe">
// handler for work with sessions
// </copyright>
// -----------------------------------------------------------------------
namespace WebServer.BusinessLogic.Handlers
{
    using WebServer.BusinessLogic.Web;

    /// <summary>
    /// Handles Session cookieless requests.
    /// For example, path of the file in GET method ca be: /{12345}/
    /// </summary>
    public class SessionHandler : Handler
    {
        private ISessionManager _sessionManager;

        public SessionHandler(ISessionManager m = null)
        {
            if (m == null)
            {
                m = SessionManager.Instance;
            }
            _sessionManager = m;
        }

        /// <summary>
        /// Process http request for sessions
        /// </summary>
        /// <param name="request">http request</param>
        /// <returns>http response</returns>
        public override Response Handle(Request request)
        {
            // create empty Session to fill it according to IsCookieless value
            Session session = null;

            // check for [12345] in path
            var path = System.Web.HttpUtility.UrlDecode(request.HttpPath);
            if (path.StartsWith("/[") && _sessionManager.IsCookieless)
            {
                // remove first 2 chars
                var sessionValue = path.Substring(2);
                
                // find ending
                int idxEnd = sessionValue.IndexOf("]");
                if (idxEnd > 0)
                {
                    // save new path without session
                    string newPath = sessionValue.Substring(idxEnd + 1);

                    // clean request's httpPath for next handlers
                    request.HttpPath = newPath;
                    
                    // get real sessionValue
                    sessionValue = sessionValue.Remove(idxEnd);
                    
                    // see if session with this value is valid
                    session = _sessionManager.GetSessionByKey(sessionValue, request);
                }
            }

            // check for cookie
            if (!_sessionManager.IsCookieless)
            {
                session = _sessionManager.GetCurrentSession(request);
            }

            // got session
            if (session != null)
            {
                request.SessionKey = session.SessionKey;
            }

            // pass it to the next handlers
            return this.NextHandler.Handle(request);
        }
    }
}
